<?php
class Search_m extends MY_Model{
		

	public function __construct(){
		parent::__construct();
	}

	
	function block($title,$data){
		
		$modules = array();
		foreach($data->modules as $module){
			$modules[] = array('value'=>$module,'text'=>$module);
		}
		return $this->template
			->set_layout(FALSE)
			->set(
				array(
					'title' => $title,
					'modules' => $modules
				)
			)
			->build('block/search');
	}
	
	function result( $module , $keyword,$limit = 1 ){
		$select_shop = 'a.id,l.title,l.slug,l.price,a.image';
		$select_categories = 'a.id,l.title,l.slug';
		
		$table_search = array();
		$this->_table = 'modules';
		$this->db->where('status',1);
		$module_m = parent::get($module);
		
		
		$model = array();
		if($module_m){
			$table_search = (array)json_decode($module_m->table_search);
			foreach($table_search as $key=>$value){
				$select = "";
				//shop product
				if(isset($value->keywords)){
					$select = $select_shop;
				}
				else{ // shop categories
					$select = $select_categories;
				}
				$is_keyword = NULL;
				$this->_table = $key.' a';
				$table_lang = $key.'_lang l';
				$this->db->select($select);
				$this->db->join($table_lang , 'l.id = a.id and l.lang = \''.$this->_lang.'\'');
//				$this->db->where('l.lang',$this->_lang);
				$this->db->like('l.title',$keyword);
				$this->db->or_like('l.slug',$keyword);
				if(isset($value->keywords)){//product
					$is_keyword = true;
					$this->db->or_like('l.keywords',$keyword);
				}				
				$this->db->limit($limit);
				$model[$key] = parent::get_all();
//				echo $this->db->last_query();

				$model[$key.'_page'] = $this->total_row($key,$keyword,$is_keyword,$limit);
				//print_r($model[$key.'_page']);exit;
			}
		}
		$model['keyword'] = $keyword;
		return $model;
	}
	//total row
	function total_row($table,$keyword, $is_keyword = NULL,$limit){
		$select_shop = 'a.id,l.title,l.slug,l.price,a.image';
		$select_categories = 'a.id,l.title,l.slug';
		$select = '';
		if(isset($is_keyword)){
			$select = $select_shop;
		}
		else
			$select = $select_categories;
			
		$model = array('total'=>0,'total_page'=>0,'size'=>$limit,'index'=>0);
		
		
		$this->_table = $table.' a';
		$table_lang = $table.'_lang l';
		$this->db->select($select);
		$this->db->join($table_lang , 'l.id = a.id and l.lang = \''.$this->_lang.'\'');
		$this->db->like('l.title',$keyword);
		$this->db->or_like('l.slug',$keyword);
		if(isset($is_keyword)){
			$this->db->or_like('l.keywords',$keyword);
//			$this->db->or_like('l.keywords',$keyword);
		}			
		$model['total'] =  $this->db->count_all_results($this->_table);
		$model['total_page'] = (int)($model['total'] / $limit )  ;//3,5 => 3, 4,1=>1
		$s = ($model['total'] % $limit ) > 0 ? 1 : 0;
		$model['total_page']  += $s;
		return $model;
	}
	
}